package com.gomtel.smartdevice.ui.activity.tools;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.gomtel.smartdevice.R;
import com.gomtel.smartdevice.base.WatchAppBaseActivity;
import com.gomtel.smartdevice.global.DataClass;
import com.gomtel.smartdevice.global.WatchApplication;
import com.gomtel.smartdevice.moudle.event.CommonEvent;
import com.gomtel.smartdevice.moudle.event.EventCode;
import com.gomtel.smartdevice.moudle.rxtools.EventBusUtil;
import com.gomtel.smartdevice.ui.dialog.ShowDialog;
import com.gomtel.smartdevice.utils.LogUtil;
import com.gomtel.smartdevice.utils.SystemUtil;
import com.gomtel.smartdevice.widget.LocationGeoHasher;
import com.gomtel.smartdevice.widget.share.JShareSetting;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.qqmodel.QZone;
import cn.jiguang.share.wechat.Wechat;

/**
 * Created by Administrator on 2018/6/19 0019.
 * 路程显示
 */

public class LocationActivity extends WatchAppBaseActivity implements View.OnClickListener, BaiduMap.OnMapClickListener, PlatActionListener {

    @BindView(R.id.map_view)
    MapView mapView;
    @BindView(R.id.begin)
    TextView begin;
    @BindView(R.id.current_time)
    TextView current_time;
    @BindView(R.id.standard_time)
    TextView standard_time;
    @BindView(R.id.tempo)
    TextView tempo;
    @BindView(R.id.calory)
    TextView calory;
    @BindView(R.id.distance)
    TextView distance;
    @BindView(R.id.continue_)
    TextView continue_;
    @BindView(R.id.stop_)
    TextView stop_;
    @BindView(R.id.befor_layout)
    LinearLayout befor_layout;
    @BindView(R.id.img_btn_black)
    ImageButton img_btn_black;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.title_about)
    ImageButton title_about;

    private BaiduMap baiduMap;
    private BDLocation bdLocation;
    private int mCurrentDirection = 0;
    private boolean LocationStatus = false;
    private SensorManager mSensorManager;
    private Double lastX = 0.0;
    private Polyline mPolyline;

    private List<LatLng> points = new ArrayList<>();
    private LocationGeoHasher locationGeoHasher;
    private double distanceAll = 0; //Km
    private DecimalFormat decimalFormat;
    private int CurrentTime = 1;

    private boolean isPause = false;//是否暂停
    private long currentSecond = 0;//当前毫秒数
    private ShowDialog showDialog;
    private int select_value = 30;

    private int CurrentCalor = 0;
    private PopupWindow popupWindow;
    private JShareSetting jShareSetting;
    private String ShareImagePath;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    current_time.setText(new StringBuffer().append(SystemUtil.getFormatHMS(currentSecond)).append("/").toString());
                    EventBusUtil.sendEvent(new CommonEvent(EventCode.EXERCISE));
                    timeRunable();
                    break;
                case 1:
                    standard_time.setText("00:00:00/");
                    initViewStuatus(2);
                    drawLine(points);
                    break;
            }
        }
    };

    @Override
    protected void registerEvent(CommonEvent commonevent) {
        switch (commonevent.getCode()) {
            case EventCode.LOCATION:
                bdLocation = (BDLocation) commonevent.getObject();
                initBaiDuLocation();
                break;
            case EventCode.SELECT_LOOP:
                select_value = commonevent.getTemp_value();
                standard_time.setText(new StringBuffer().append(select_value).append("分钟"));
                initViewStuatus(0);
                break;

        }
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_location;
    }

    @Override
    protected void initClass() {
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);// 获取传感器管理服务
        locationGeoHasher = new LocationGeoHasher();
        decimalFormat = new DecimalFormat("0.00");
        showDialog = ShowDialog.newInstance();
        jShareSetting = new JShareSetting(this);
    }

    @Override
    protected void initData() {
        CurrentCalor = DataClass.CurrentTotalCalories;
        File imageFile = jShareSetting.copyResurces("ic_launcher.png", "ic_launcher.png", 0);
        ShareImagePath = imageFile.getAbsolutePath();
    }

    @Override
    protected void initView() {
        title_name.setText("轨迹");
        title_about.setVisibility(View.VISIBLE);
        title_about.setImageResource(R.drawable.share_icon);
        baiduMap = mapView.getMap();
        baiduMap.setMyLocationEnabled(true);
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, null));
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.overlook(0);
        baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(15).build()));

    }

    @Override
    protected void initListener() {
        baiduMap.setOnMapClickListener(this);
        begin.setOnClickListener(this);
        continue_.setOnClickListener(this);
        stop_.setOnClickListener(this);
        img_btn_black.setOnClickListener(this);
        title_about.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.begin:
                if (LocationStatus) {
                    initViewStuatus(1);
                } else {
                    showDialog.showLoopDialog(this, select_value);
                }
                break;
            case R.id.continue_:
                initViewStuatus(3);
                break;
            case R.id.stop_:
                initViewStuatus(2);
                drawLine(points);
                break;
            case R.id.img_btn_black:
                finish();
                break;
            case R.id.title_about:
                showPopWindows();
                break;
            case R.id.layout_qq:
                shareType(0);
                break;
            case R.id.layout_wechat:
                shareType(2);
                break;
            case R.id.layout_zq:
                shareType(1);
                break;

        }
//        toastUtil.showToast("isPause ：" + isPause);
    }

    //终点Mark
    private void enbMark(LatLng latLng) {
        MarkSetting(latLng, R.drawable.ic_map_red_tag);
    }

    //起点Mark
    private void startMark(LatLng latLng) {
        MarkSetting(latLng, R.drawable.ic_map_tag);
    }

    //定位
    private void initBaiDuLocation() {
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(bdLocation.getRadius())
                .direction(mCurrentDirection).latitude(bdLocation.getLatitude())
                .longitude(bdLocation.getLongitude()).build();
        if (baiduMap != null)
            baiduMap.setMyLocationData(locData);
        points.add(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()));
        calculateDistance(points);
    }

    //Mark 设置
    private void MarkSetting(LatLng latLng, int id) {
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(id);
        OverlayOptions option = new MarkerOptions().position(latLng).icon(bitmap).draggable(true);
        baiduMap.addOverlay(option);
    }

    //视图设置
    private void MapStatus(int index) {
        if (mPolyline != null)
            mPolyline.remove();
        baiduMap.clear();
        MapStatus mMapStatus = new MapStatus.Builder().target(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude())).zoom(index).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        baiduMap.setMapStatus(mMapStatusUpdate);
    }

    //路程线
    private void drawLine(List<LatLng> points) {
        try {
            if (mPolyline != null) {
                mPolyline.remove();
            } else {
                startMark(points.get(0));
                enbMark(points.get(points.size() - 1));
            }
            OverlayOptions ooPolyline = new PolylineOptions().width(6).color(getResources().getColor(R.color.color_motion_blue)).points(points);
            mPolyline = (Polyline) baiduMap.addOverlay(ooPolyline);
            locationGeoHasher.calculateDistance(points.get(0), points.get(points.size() - 1), baiduMap);
        } catch (Exception e) {
            LogUtil.e(TAG, "Exception : " + e.toString());
        }
    }

    //距离计算
    private void calculateDistance(List<LatLng> points) {
        LatLng latLngCurrent = null;
        LatLng latLngBefor = null;
        if (points.size() > 1) {
            latLngCurrent = points.get(points.size() - 1);
            latLngBefor = points.get(points.size() - 2);
        } else if (points.size() == 1) {
            latLngCurrent = points.get(points.size() - 1);
            latLngBefor = points.get(0);
        }
        distanceAll = distanceAll + locationGeoHasher.getDistance(latLngBefor.longitude, latLngBefor.latitude, latLngCurrent.longitude, latLngCurrent.latitude);
        String formatDistance = decimalFormat.format(distanceAll); //里程
        String formatTempo = decimalFormat.format((distanceAll / CurrentTime * 60)); //速度
        tempo.setText(formatTempo);
        calory.setText(String.valueOf(DataClass.CurrentTotalCalories - CurrentCalor));
        distance.setText(formatDistance);
        LogUtil.e(TAG, "formatDistance : " + formatDistance);
        LogUtil.e(TAG, "formatTempo : " + formatTempo);
    }

    //计时器
    private void timeRunable() {
        WatchApplication.executorService.submit(new Runnable() {
            @Override
            public void run() {
                currentSecond = currentSecond + 1000;
                CurrentTime = (int) currentSecond / 1000;
                LogUtil.e(TAG, "isPause : " + isPause);
                if (!isPause) {
                    try {
                        if (currentSecond < 60 * 12 * 1000) {
                            Thread.sleep(999);
                            handler.sendEmptyMessage(0);
                        } else {
                            handler.sendEmptyMessage(1);
                        }
                    } catch (Exception e) {
                        LogUtil.e(TAG, "Exception : " + e.toString());
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    //控件状态
    private void initViewStuatus(int status) {
        switch (status) {
            case 0:
                points.clear();
                begin.setText("暂停");
                LocationStatus = true;
                isPause = false;
                tempo.setText("0000");
                calory.setText("0000");
                distance.setText("0000");
                distanceAll = 0;
                CurrentTime = 0;
                MapStatus(15);
                timeRunable();
                break;
            case 1:
                isPause = true;
                befor_layout.setVisibility(View.VISIBLE);
                begin.setVisibility(View.GONE);
                break;
            case 2:
                begin.setText("开始");
                LocationStatus = false;
                isPause = true;
                befor_layout.setVisibility(View.GONE);
                begin.setVisibility(View.VISIBLE);
                current_time.setText("00:00:00/");
                currentSecond = 0;
                break;
            case 3:
                isPause = false;
                handler.sendEmptyMessage(0);
                begin.setText("暂停");
                befor_layout.setVisibility(View.GONE);
                begin.setVisibility(View.VISIBLE);
                break;
        }
    }

    //分享pop
    public void showPopWindows() {
        LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        ViewGroup menuView = (ViewGroup) mLayoutInflater.inflate(R.layout.custom_popwindow_title, null, true);
        View layout_qq = menuView.findViewById(R.id.layout_qq);
        View layout_wechat = menuView.findViewById(R.id.layout_wechat);
        View layout_zq = menuView.findViewById(R.id.layout_zq);
        layout_qq.setOnClickListener(this);
        layout_wechat.setOnClickListener(this);
        layout_zq.setOnClickListener(this);
        popupWindow = new PopupWindow(menuView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(true);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;
        popupWindow.showAtLocation(menuView, Gravity.TOP, width, findViewById(R.id.title_layout).getHeight());
        popupWindow.update();
    }

    private void shareType(int type) {
        ShareParams shareParams = new ShareParams();
        shareParams.setShareType(Platform.SHARE_TEXT);//分享类型
        shareParams.setTitle("全球健康链"); //分享标题
        shareParams.setText("今日运动轨迹");//分享内容
        shareParams.setUrl("https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%8F%AF%E7%88%B1%E5%9B%BE%E7%89%87&step_word=&hs=0&pn=20&spn=0&di=81947805940&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=171918920%2C1546681003&os=1619126843%2C3041949405&simid=3407526154%2C101558968&adpicid=0&lpn=0&ln=1989&fr=&fmq=1520068032787_R&fm=rs7&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=%E5%9B%BE%E7%89%87&objurl=http%3A%2F%2Fwww.qqpk.cn%2FArticle%2FUploadFiles%2F201410%2F20141015092732373.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bqqrh_z%26e3BvgAzdH3FA6ptvsjAzdH3Fp7rtwgAzdH3Fda898aAzdH3F8m89c_z%26e3Bip4&gsm=0&rpstart=0&rpnum=0");//分享链接
        shareParams.setImagePath(ShareImagePath);//分享链接
        switch (type) {
            case 0:
                shareParams.setShareType(Platform.SHARE_WEBPAGE);//分享类型
                JShareInterface.share(QQ.Name, shareParams, this);
                break;
            case 1:
                shareParams.setShareType(Platform.SHARE_WEBPAGE);//分享类型
                JShareInterface.share(QZone.Name, shareParams, this);
                break;
            case 2:
                JShareInterface.share(Wechat.Name, shareParams, this);
                break;
        }
        popupWindow.dismiss();
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {

    }

    @Override
    public void onError(Platform platform, int i, int i1, Throwable throwable) {

    }

    @Override
    public void onCancel(Platform platform, int i) {

    }

    //罗盘仪
    @Override
    public void onSensorChanged(SensorEvent event) {
        super.onSensorChanged(event);
        double x = event.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0 && bdLocation != null) {
            mCurrentDirection = (int) x;
            // 此处设置开发者获取到的方向信息，顺时针0-360
            MyLocationData build = new MyLocationData.Builder()
                    .accuracy(bdLocation.getRadius())
                    .direction(mCurrentDirection)
                    .latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude()).build();
            baiduMap.setMyLocationData(build);
        }
        lastX = x;
    }

    @Override
    public void onMapClick(LatLng latLng) {
        toastUtil.showToast("latitude : " + latLng.latitude + " - " + "longitude : " + latLng.longitude);
        points.add(latLng);
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI);
        super.onResume();
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        initViewStuatus(2);
        baiduMap.setMyLocationEnabled(false);
        super.onDestroy();
    }


}
